package com.liuyk.commonlib.utility;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;

/**
 * 图片颜色更换工具
 * <p>
 * Created by liuyk on 2015/12/10.
 */
public class PictureColorTransform {

    //提取图像Alpha位图
    public static Bitmap getAlphaBitmap(Bitmap bitmap, int color) {
        //BitmapDrawable的getIntrinsicWidth（）方法，Bitmap的getWidth（）方法
        //注意这两个方法的区别
        //mBitmapDrawable.getIntrinsicWidth(), mBitmapDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        final Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        //用一个指定的Bitmap 构造一个画布 Bitmap必须是可变的
        final Canvas mCanvas = new Canvas(canvasBitmap);
        final Paint mPaint = new Paint();
        mPaint.setColor(color);

        //从原位图中提取只包含alpha的位图，在画布上（mAlphaBitmap）绘制alpha位图
        mCanvas.drawBitmap(bitmap.extractAlpha(), 0, 0, mPaint);
        return canvasBitmap;
    }

    /**
     * 将bitmap的底背景颜色，转化成指定的颜色，并且保持内容部分不变
     *
     * @param bitmap
     * @return
     */
    public static Bitmap bitmapBackgroundTransformer(Bitmap bitmap, int backgroundColor, int paintColor) {

        /**
         * 1.如果保存格式是JPEG的话，那么缩略图和图片 底层颜色全都是黑色背景
         *
         * 2.如果保存格式是PNG的话，那么缩略图是白色，图片依然是黑色背景底
         *
         * 分析：
         * 问题出现的原因：在保存Bitmap为图片的时候，没有内容的区域，会默认为黑色填充，所以导致图片底是黑色的
         * 解决办法：最安全的解决方法
         * step1：首先创建一个纯白色的Bitmap
         * step2：用bitmap.extractAlpha()提取原Bitmap的内容部分
         * step3：用Canvas将原Bitmap的内容部分，绘制到 纯白色Bitmap上
         */
        Bitmap b = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        int height = b.getHeight();
        int width = b.getWidth();
        int[] pixels = new int[width * height];
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++) {
                int index = i * width + j;
                pixels[index] = backgroundColor;
            }
        b.setPixels(pixels, 0, width, 0, 0, width, height);

        //将原bitmap的内容区域，绘制到纯白色bitmap上
        Canvas canvas = new Canvas(b);
        Paint paint = new Paint();
        paint.setColor(paintColor);
        canvas.drawBitmap(bitmap.extractAlpha(), 0, 0, paint);
        return b;
    }

    public static Bitmap pictureTransform(Context context, int imageId, int color) {
        final Drawable drawable = context.getResources().getDrawable(imageId);
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ALPHA_8);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        bitmap = bitmapBackgroundTransformer(bitmap, Color.TRANSPARENT, color);
        return bitmap;
    }
}
